package com.hecj.common.lib.util;

import com.hecj.common.lib.encryption.MD5;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 接口签名工具类
 * @author hecj
 *
 */
public class SignKit {
	private static Logger log = LoggerFactory.getLogger(SignKit.class);
	// 签名字段
	final static String SIGN_FIELD = "sign";

	/**
	 * 接口签名验证
	 * @param json
	 * @return
	 */
	public static boolean checkSign(JSONObject json){
		// 签名校验
		String mSign = SignKit.sign(json);
		String sign = json.getString("sign");
		if(!mSign.equals(sign)){
			log.error("mSign {}",mSign);
			return false;
		}
		return true;
	}

	/**
	 * 签名
	 * @param obj
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String sign(Object obj) {
		if(obj instanceof Map) {
			return MD5.md5crypt(Constant.ApiDesKey+getDictStr((Map)obj));
		}
		if(obj instanceof JSONObject) {
			return MD5.md5crypt(Constant.ApiDesKey+getDictStr((JSONObject)obj));
		}
		throw new RuntimeException("暂时不支持此类型生成签名,"+obj.getClass());
	}
	
	/**
	 * JSONObject字段排序拼接
	 * @param obj
	 * @return
	 */
	public static String getDictStr(JSONObject obj) {
		List<String> keys = new ArrayList<String>(obj.keySet());
		keys.remove(SIGN_FIELD);
		Collections.sort(keys);
		StringBuffer str = new StringBuffer();
		for(String key : keys) {
			Object value = obj.get(key);
			if(value == null) {
				value = "";
			}
			str.append(String.valueOf(value));
		}
		return str.toString();
	}
	
	/**
	 * Map字段排序拼接
	 * @param obj
	 * @return
	 */
	public static String getDictStr(Map<String,Object> obj) {
		List<String> keys = new ArrayList<String>(obj.keySet());
		keys.remove(SIGN_FIELD);
		Collections.sort(keys);
		StringBuffer str = new StringBuffer();
		for(String key : keys) {
			Object value = obj.get(key);
			if(value == null) {
				value = "";
			}
			str.append(String.valueOf(value));
		}
		return str.toString();
	}
	
}
